'use strict';
const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  const {
    taskId,
    content,
    type = 'text',
    receiverId: clientReceiverId, 
    title = '',
    status = 'pending' 
  } = event;

  if (!event.uniIdToken) {
    console.error('[sendChatMessage] Invocation failed, uniIdToken is missing.');
    return {
      code: 401,
      errCode: 'uni-id-token-required',
      msg: 'User not logged in or token is invalid'
    };
  }

  const uniIDIns = uniID.createInstance({ context });

  // content 是必须的，taskId 是可选的（客服聊天可能没有关联任务）
  if (!content) {
    return { code: 400, msg: 'Missing content' };
  }

  try {
    const { uid: senderId } = await uniIDIns.checkToken(event.uniIdToken);
    if (!senderId) {
      return { code: 401, msg: 'User not logged in' };
    }

    const user = await db.collection('uni-id-users').doc(senderId).field({
      _id: 1,
      nickname: 1,
      'avatar_file.url': 1
    }).get();
    
    if (!user.data || user.data.length === 0) {
        return { code: 404, msg: 'Sender user does not exist' };
    }
    const senderInfo = user.data[0];
    const senderAvatar = (senderInfo.avatar_file && senderInfo.avatar_file.url) ? senderInfo.avatar_file.url : '/static/images/default-avatar.png';


    let receiverId, receiverNickname, receiverAvatar;
    
    if (clientReceiverId) {
        // 有明确的接收者ID（客服聊天或私信）
        receiverId = clientReceiverId;
        
        // 如果是发送给客服（admin）
        if (clientReceiverId === 'admin') {
            receiverNickname = '客服小助手';
            receiverAvatar = '';
        } else {
            // 获取接收者信息
            try {
                const receiverResult = await db.collection('uni-id-users')
                    .doc(clientReceiverId)
                    .field({ nickname: true, avatar_file: true })
                    .get();
                
                if (receiverResult.data && receiverResult.data.length > 0) {
                    const receiverInfo = receiverResult.data[0];
                    receiverNickname = receiverInfo.nickname || '用户';
                    receiverAvatar = (receiverInfo.avatar_file && receiverInfo.avatar_file.url) ? receiverInfo.avatar_file.url : '';
                } else {
                    receiverNickname = '用户';
                    receiverAvatar = '';
                }
            } catch (error) {
                console.log('获取接收者信息失败:', error);
                receiverNickname = '用户';
                receiverAvatar = '';
            }
        }
    } else if (taskId) {
        // 通过任务ID获取接收者（任务聊天）
        const task = await db.collection('tasks').doc(taskId).field({ userId: 1 }).get();
        if (!task.data || task.data.length === 0) {
            return { code: 404, msg: 'Associated task does not exist' };
        }
        receiverId = task.data[0].userId;
        
        // 获取任务发布者信息
        try {
            const receiverResult = await db.collection('uni-id-users')
                .doc(receiverId)
                .field({ nickname: true, avatar_file: true })
                .get();
            
            if (receiverResult.data && receiverResult.data.length > 0) {
                const receiverInfo = receiverResult.data[0];
                receiverNickname = receiverInfo.nickname || '用户';
                receiverAvatar = (receiverInfo.avatar_file && receiverInfo.avatar_file.url) ? receiverInfo.avatar_file.url : '';
            } else {
                receiverNickname = '用户';
                receiverAvatar = '';
            }
        } catch (error) {
            console.log('获取接收者信息失败:', error);
            receiverNickname = '用户';
            receiverAvatar = '';
        }
    } else {
        // 既没有接收者ID也没有任务ID
        return { code: 400, msg: 'Missing receiverId or taskId' };
    }

    if (senderId === receiverId) {
        return { code: 200, msg: 'Message sent (no actual operation)' }; 
    }

    const messageData = {
      taskId,
      type,
      senderId,
      senderAvatar: senderAvatar,
      senderNickname: senderInfo.nickname || '用户',
      receiverId,
      receiverNickname: receiverNickname || '用户',
      receiverAvatar: receiverAvatar || '',
      content,
      createTime: new Date(),
      status: 'unread'
    };

    // 如果是图片消息，同时保存到imageUrl字段
    if (type === 'image') {
      messageData.imageUrl = content;
      // 对于图片消息，content字段可以保存为简短描述
      messageData.content = '[图片]';
    }

    if (type === 'card') {
      messageData.title = title;
      messageData.status = status;
    }

    // 始终保存到chatMessages表
    const result = await db.collection('chatMessages').add(messageData);
    
    // 如果是客服消息（发送者或接收者是admin/customer_service），同时保存到客服消息表
    const isCustomerServiceMessage = receiverId === 'admin' || 
                                     receiverId === 'customer_service' || 
                                     senderId === 'admin' || 
                                     senderId === 'customer_service';
    
    if (isCustomerServiceMessage) {
      // 构建客服消息数据（使用统一格式）
      const customerServiceMessageData = {
        messageType: type,
        senderId: senderId,
        senderNickname: senderInfo.nickname || '用户',
        senderAvatar: senderAvatar,
        receiverId: receiverId === 'admin' ? 'customer_service' : receiverId,
        receiverNickname: receiverNickname,
        receiverAvatar: receiverAvatar,
        content: messageData.content,
        createTime: new Date(),
        status: 'sent',
        taskId: taskId
      };
      
      // 如果是图片消息，添加imageUrl字段
      if (type === 'image') {
        customerServiceMessageData.imageUrl = messageData.imageUrl || content;
      }
      
      // 保存到客服消息表
      try {
        await db.collection('customer-service-messages').add(customerServiceMessageData);
        console.log('[sendChatMessage] 客服消息已同步保存到customer-service-messages表');
      } catch (csError) {
        console.error('[sendChatMessage] 保存客服消息失败:', csError);
        // 不影响主流程，只记录错误
      }
    }

    return {
      code: 200,
      msg: 'Message sent successfully',
      data: {
        _id: result.id,
        ...messageData
      }
    };

  } catch (error) {
    console.error('Failed to send message:', error);
    if (error.code && error.code.startsWith('uni-id-')) {
        return { errCode: error.code, msg: error.message };
    }
    return {
      code: 500,
      msg: 'Server internal error',
      error: error.message
    };
  }
}; 